package com.education.teacher.redis;

import com.education.util.SerialUtil;
import org.apache.commons.codec.binary.Base64;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPubSub;

import java.io.Serializable;


/**
 * Created by lzh on 2017/8/20.
 */
public class RedisPubSubManager {

    private JedisPool jedisPool;

    private String channels;


    /**
     * 创建一个发布-订阅通道
     * @param jedisPool
     * @param jedisPubSub
     * @param channels
     */
    public RedisPubSubManager(JedisPool jedisPool,JedisPubSub jedisPubSub,String channels){
        this.jedisPool=jedisPool;
        this.channels=channels;
       Jedis jedis= jedisPool.getResource();
       new Thread(new Runnable() {
           @Override
           public void run() {
               jedis.subscribe(jedisPubSub,channels);//订阅模式是单线程，会阻塞。必须新开线程
           }
       }).start();

    }

    /**
     * 发布消息
     * @param msg
     */
    public void pubMessage(Serializable msg){
        try (Jedis jedis=jedisPool.getResource()){
            String str=Base64.encodeBase64String(SerialUtil.Object2Bytes(msg));//必须使用base64编码成String 使用new String会报错
            jedis.publish(this.channels,str);
        }
    }
}
